package com.docman.dao;
import java.sql.*;
import java.util.ArrayList;

import com.docman.domainmodel.DocumentBean;
import com.docman.domainmodel.UserBean;

import com.docman.dbconnect.*;
public class AdvancedSearchDAO {

	static Connection currentCon = null;
	static ResultSet rs = null;
	
	//gets search criteria and returns corresponding documents as arraylist.
	public static ArrayList<DocumentBean> search(ArrayList<String> searchCriteria){

	ArrayList<DocumentBean> docs =new ArrayList<DocumentBean>();
	String query="SELECT DISTINCT * FROM DOCUMENTS WHERE ";
	boolean isFirst = true;
	String fileName = searchCriteria.get(0);
	String tag = searchCriteria.get(1);
	String uploader =searchCriteria.get(2);
	String time1 = searchCriteria.get(3);
	String time2= searchCriteria.get(4);
	String singleQuote = "\'";
	
	if(!fileName.equals("")){
		query +="docName LIKE" +singleQuote + "%"+ fileName + "%" +singleQuote ;
		isFirst= false;
	}	
	if(!tag.equals("")){
		if(isFirst){
		query +="tag ="+singleQuote+ tag + singleQuote;
		isFirst= false;
		}
		else
		query +=" AND "+"tag ="+ singleQuote + tag + singleQuote;
	}
	if(!uploader.equals("")){
		if(isFirst){
		query +="uploader ="+singleQuote + uploader + singleQuote;
		isFirst= false;
		}
		else
		query +=" AND "+"uploader ="+singleQuote + uploader + singleQuote;
	}
	if(!time1.equals("") && !time2.equals("")){
		if(isFirst){
		query +="uploadDate BETWEEN "+ singleQuote +time1 + singleQuote +"AND"+ singleQuote + time2 + singleQuote;
		isFirst= false;
		}
		else
		query +=" AND "+"uploadDate BETWEEN "+ singleQuote + time1 + singleQuote +" AND "+ singleQuote + time2 + singleQuote;
	}
	
	query += " ORDER BY totalRating";
	try{
		currentCon =ConnectionManager.getInstance().getConnection();
		Statement stmt =currentCon.createStatement();
		//System.out.println("query :"+ query);
		rs= stmt.executeQuery(query);
		
		while(rs.next()){
			UserBean user = new UserBean();
			DocumentBean doc =new DocumentBean();
			doc.setDocId(rs.getInt("docId"));
			doc.setComment(rs.getString("comment"));
			doc.setDocName(rs.getString("docName"));
			doc.setRating(rs.getInt("totalRating"));
			doc.setRatingCount(rs.getInt("ratingCount"));
			doc.setTag(rs.getString("tag"));
			doc.setTitle(rs.getString("title"));
			doc.setUploadDate(rs.getDate("uploadDate"));
			user.setUserName(rs.getString("uploader"));
			doc.setUploader(user.getUserName());
			doc.setDocPath(rs.getString("filePath"));
			docs.add(doc);
		}
		rs.close();
		stmt.close();
	}
	catch(Exception e){
		System.out.println("Advanced Search Failed "+e);
	}
	return	docs;
	}

}
